﻿using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZFSData;
using ZFSData.InterFace.User;
using ZFSDomain.Common.CoreLib;
using ZFSDomain.Common.CoreLib.Helper;
using ZFSDomain.Common.Domain;
using ZFSDomain.Interface.User;
using ZFSDomain.Service;
using ZFSDomain.SysModule;

namespace ZFSDomain.ViewModel.Group
{

    /// <summary>
    /// 用户组 
    /// </summary>
    public class GroupViewModel : BaseOperation
    {
        #region 属性

        private ObservableCollection<tb_Group> groupModelList;

        /// <summary>
        /// 组数据集合
        /// </summary>
        public ObservableCollection<tb_Group> GroupModelList
        {
            get { return groupModelList; }
            set { groupModelList = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 菜单列表
        /// </summary>
        public List<MenuGroupModel> MenuGroupModels { get; set; }

        #endregion

        public override void InitViewModel()
        {
            GroupModelList = new ObservableCollection<tb_Group>();
            MenuGroupModels = new List<MenuGroupModel>();
            InitMenuTree();
            base.InitViewModel();
            this.Query();
        }

        /// <summary>
        /// 初始化菜单树
        /// </summary>
        private void InitMenuTree()
        {
            var treeList = ZFSBridge.BridgeFactory.GetMenuBridge().GetMenuTrees();

            LoadingTreeList(treeList, new MenuGroupModel(), null);
        }

        /// <summary>
        /// 初始化菜单权限目录
        /// </summary>
        /// <param name="menuTrees"></param>
        /// <param name="menuGroup"></param>
        /// <param name="parentID"></param>
        private void LoadingTreeList(List<View_MenuTree> menuTrees, MenuGroupModel menuGroup, object parentID)
        {
            var ParentMenuList = menuTrees.Where(q => q.ParentID.Equals(parentID)).ToList();

            if (ParentMenuList.Count == 0) return;

            foreach (var p in ParentMenuList)
            {
                if (p.ParentID == null)
                {
                    MenuGroupModel groupModel = new MenuGroupModel()
                    {
                        ID = p.isid,
                        MenuName = p.MenuName,
                        MenuCode = p.MenuCode,
                        ParentId = 0,
                        AuthValue = p.AuthorityValue
                    };
                    MenuGroupModels.Add(groupModel);
                    LoadingTreeList(menuTrees, groupModel, p.isid);
                }
                else
                {
                    var node = menuGroup.Nodes.FirstOrDefault(t => t.MenuName.Equals(p.MenuName));

                    if (node == null) //如果子节点不存在就增加进去
                    {
                        MenuGroupModel groupModel = new MenuGroupModel();
                        groupModel.ID = menuGroup.ID + 1;
                        groupModel.MenuName = p.MenuName;
                        groupModel.MenuCode = p.MenuCode;
                        groupModel.ParentId = Convert.ToInt32(parentID);

                        //获取到菜单名称对应的权限值列表
                        var authitemList = menuTrees.Where(t => t.MenuName.Equals(p.MenuName)).ToList();

                        //将该列表添加进groupModel的子集中
                        foreach (var a in authitemList)
                        {
                            groupModel.Nodes.Add(new MenuGroupModel()
                            {
                                MenuName = a.AuthorityName,
                                MenuCode = a.MenuCode,
                                AuthValue = a.AuthorityValue,
                                ParentId = groupModel.ID
                            });
                        }
                        menuGroup.Nodes.Add(groupModel);
                    }
                }
            }
        }


        public override void Query()
        {
            try
            {
                var GroupList = ZFSBridge.BridgeFactory.GetGroupBridge().GetGroups(SearchText);

                GroupModelList.Clear();
                GroupList.ForEach((arg) => GroupModelList.Add(arg));
            }
            catch (Exception ex)
            {
                Msg.Error(ex.Message);
            }
        }

        /// <summary>
        /// 新增用户组
        /// </summary>
        public override void Add()
        {
            try
            {
                GroupDialogViewModel view = new GroupDialogViewModel();
                view.IsReadOnly = false;
                view.Group = new tb_Group();
                view.MenuGroupModels = this.MenuGroupModels;
                var funcList = ZFSBridge.BridgeFactory.GetGroupBridge().GetGroupFuncs(view.Group.GroupCode); //获取组权限数据

                #region Binding GroupAuthValue

                funcList.ForEach(t =>
                {
                    view.MenuGroupModels.ForEach(q =>
                    {
                        if (q.MenuCode.Equals(t.MenuCode))
                            q.IsChecked = true;
                        else
                        {
                            q.Nodes.ForEach(w =>
                            {
                                if (w.MenuCode.Equals(t.MenuCode))
                                {
                                    w.IsChecked = true;
                                    w.Nodes.ForEach(s =>
                                    {
                                        if ((t.Authorities & s.AuthValue) == s.AuthValue)
                                            s.IsChecked = true;
                                    });
                                }
                            });
                        }
                    });
                });

                #endregion

                view.CaCheUser = new List<View_GroupUser>();
                var dialog = ServiceProvider.Instance.Get<IGroupDialog>();
                dialog.BindViewModel(view);
                var result = dialog.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    GroupModelList.Add(view.Group);
                }
            }
            catch (Exception ex)
            {
                Msg.Error(ex.Message);
            }
        }

        /// <summary>
        /// 编辑用户组
        /// </summary>
        public override void Edit()
        {
            if (!this.GetButtonAuth(Authority.EDIT)) return;

            if (CurrentRow != null)
            {
                try
                {
                    GroupDialogViewModel view = new GroupDialogViewModel();
                    view.IsReadOnly = true;
                    view.Group = DeepCopy.CopyByReflect((tb_Group)CurrentRow);
                    view.MenuGroupModels = new List<MenuGroupModel>(this.MenuGroupModels.ToArray());
                    var funcList = ZFSBridge.BridgeFactory.GetGroupBridge().GetGroupFuncs(view.Group.GroupCode); //获取组权限数据

                    #region Binding GroupAuthValue

                    funcList.ForEach(t =>
                    {
                        view.MenuGroupModels.ForEach(q =>
                        {
                            if (q.MenuCode.Equals(t.MenuCode))
                                q.IsChecked = true;
                            else
                            {
                                q.Nodes.ForEach(w =>
                                {
                                    if (w.MenuCode.Equals(t.MenuCode))
                                    {
                                        w.IsChecked = true;
                                        w.Nodes.ForEach(s =>
                                        {
                                            if ((t.Authorities & s.AuthValue) == s.AuthValue)
                                                s.IsChecked = true;
                                        });
                                    }
                                });
                            }
                        });
                    });

                    #endregion

                    view.CaCheUser = ZFSBridge.BridgeFactory.GetGroupBridge().GetGroupUsers(view.Group.GroupCode); //获取用户组
                    var dialog = ServiceProvider.Instance.Get<IGroupDialog>();
                    dialog.BindViewModel(view);
                    var result = dialog.ShowDialog();
                    if (result.HasValue && result.Value)
                    {
                        var EditGroup = GroupModelList.FirstOrDefault(t => t.isid.Equals(view.Group.isid));
                        EditGroup.GroupName = view.Group.GroupName;
                    }
                }
                catch (Exception ex)
                {
                    Msg.Error(ex.Message);
                }
            }
        }

        /// <summary>
        /// 删除用户组
        /// </summary>
        public override void Del()
        {
            if (CurrentRow != null)
            {
                tb_Group group = DeepCopy.CopyByReflect((tb_Group)CurrentRow);
                if (Msg.Question(string.Format("确认删除组:{0}?", group.GroupName)))
                {
                    bool result = ZFSBridge.BridgeFactory.GetGroupBridge().Remove(group.isid);
                    if (result)
                    {
                        var gp = GroupModelList.FirstOrDefault(t => t.isid.Equals(group.isid));
                        GroupModelList.Remove(gp);
                        Msg.Info("删除成功!");
                    }
                }
            }
            base.Del();
        }

        /// <summary>
        /// 重置
        /// </summary>
        public override void Reset()
        {
            base.Reset();
        }

    }
}
